//
//  YJWRecommendViewController.m
//  百思不得骑姐
//
//  Created by YJW on 16/10/16.
//  Copyright © 2016年 yijiang. All rights reserved.
//

#import "YJWRecommendViewController.h"
#import <AFNetworking.h>
#import <SVProgressHUD.h>
#import <MJExtension.h>
#import <MJRefresh.h>

#import "YJWRecommendCategoryCell.h"
#import "YJWCategory.h"
#import "YJWRecommendUserCell.h"
#import "YJWUser.h"

#define selectedCategory self.categories[self.categoryTableView.indexPathForSelectedRow.row]

@interface YJWRecommendViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *categoryTableView;
@property (weak, nonatomic) IBOutlet UITableView *userTableView;

/** categories   */
@property(nonatomic,strong) NSArray *categories;
/** 请求参数   */
@property(nonatomic,strong) NSMutableDictionary *paras;
/** manager   */
@property(nonatomic,strong) AFHTTPSessionManager *manager;

@end

@implementation YJWRecommendViewController

static NSString *reuseCategoryId = @"category";
static NSString *reuesUserId = @"user";

-(AFHTTPSessionManager *)manager
{
    if(!_manager){
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置标题
    self.title = @"推荐关注";
    
    //空件初始化
    [self setUpTableView];
    
    //添加刷新按钮
    [self addRefresh];
    
    //设置背景颜色
    self.view.backgroundColor = YJWBgColor;
    
    //设置左边分类
    [self loadCategories];
}

/*
 * 设置左边分类
 */
-(void)loadCategories
{
    //显示进度条
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    //向服务器请求数据，服务器返回分类数组
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"category";
    parameters[@"c"] = @"subscribe";
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.categories = [YJWCategory mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [self.categoryTableView reloadData];
        
        //设置默认选择第一行
        [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        //加载第一个分类所对应的用户
        [self.userTableView.mj_header beginRefreshing];
        
        //隐藏指示器
        [SVProgressHUD dismiss];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"数据加载失败"];
    }];
}

#pragma mark - 控件初始化
-(void)setUpTableView{
    
    [self.categoryTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YJWRecommendCategoryCell class]) bundle:nil] forCellReuseIdentifier:reuseCategoryId];
    [self.userTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YJWRecommendUserCell class]) bundle:nil] forCellReuseIdentifier:reuesUserId];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.categoryTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.userTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.userTableView.rowHeight = 56;
}

//添加刷新控件
-(void)addRefresh
{
    //添加下拉刷新控件
    self.userTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];

    //添加上拉刷新控件
    self.userTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
    self.userTableView.mj_footer.hidden = YES;
}

//下拉加载新数据
-(void)loadNewUsers
{
    YJWCategory *category = selectedCategory;
    
    //设置当前页
    category.currentPage = 1;
    
    //选中某一项分类时向服务器请求数据，服务器返回用户数组
    //请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"subscribe";
    parameters[@"category_id"] = @(category.id);
    parameters[@"page"] = @(category.currentPage);
    self.paras = parameters;
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //如果不是最后一次请求，就停止页面展示
        if (self.paras != parameters) return;
        
        //清除之前所有用户数据，防止下拉刷新时显示重复数据
        [category.users removeAllObjects];
        
        NSArray *users = [YJWUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [category.users addObjectsFromArray:users];
        
        //获取所有用户数量
        category.total = [responseObject[@"total"] integerValue];
        
        //判断是否加载所有数据
        [self.userTableView reloadData];
        
        [self.userTableView.mj_header endRefreshing];
        [self checkFooterState];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.paras != parameters) return;
        [SVProgressHUD showErrorWithStatus:@"数据加载失败"];
        [self.userTableView.mj_header endRefreshing];
    }];
}

//上拉加载更多数据
-(void)loadMoreUsers
{
    YJWCategory *c = selectedCategory;
    //设置请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"subscribe";
    parameters[@"category_id"] = @(c.id);
    parameters[@"page"] = @(++c.currentPage);
    self.paras = parameters;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //如果不是最后一次请求，就停止页面展示
            if (self.paras != parameters) return;
            
            NSArray *users = [YJWUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            [c.users addObjectsFromArray:users];
            
            [self.userTableView reloadData];
            [self checkFooterState];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (self.paras != parameters) return;
            [SVProgressHUD showWithStatus:@"加载数据失败"];
            [self.userTableView.mj_footer endRefreshing];
        }];
    });
}

//检测底部刷新控件状态
-(void)checkFooterState
{
    YJWCategory *c = selectedCategory;
    NSInteger userCount = [c users].count;
    //判断是否隐藏
    self.userTableView.mj_footer.hidden = (userCount == 0);
    
    //判断状态
    if (userCount == c.total) {
        [self.userTableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.userTableView.mj_footer endRefreshing];
    }
}

#pragma - mark <UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.categoryTableView) {
        return self.categories.count;
    }else{
        [self checkFooterState];
        return [selectedCategory users].count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.categoryTableView) {
        YJWRecommendCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseCategoryId];
        cell.category = self.categories[indexPath.row];
        return cell;
    }else{
        YJWRecommendUserCell *cell = [tableView dequeueReusableCellWithIdentifier:reuesUserId forIndexPath:indexPath];
        cell.user = [selectedCategory users][indexPath.row];
        return cell;
    }
}

#pragma mark - <UITableViewDelegate>
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.categoryTableView) {
        //优化：刚进入时停止刷新
        [self.userTableView.mj_header endRefreshing];
        [self.userTableView.mj_footer endRefreshing];
        
        YJWCategory *category = self.categories[self.categoryTableView.indexPathForSelectedRow.row];
        
        //解决重复请求问题
        if (category.users.count>0) {
            [self.userTableView reloadData];
        }else{
            //解决本类别显示其他类别内容
            [self.userTableView reloadData];
            
            //显示下拉刷新
            [self.userTableView.mj_header beginRefreshing];
        }
    }
}

//请求数据过程中，控制器被销毁，则应取消数据的处理（否则很可能会崩溃）
-(void)dealloc{
    [self.manager.operationQueue cancelAllOperations];
}

@end
